package com.smasher.domain.fragment

import android.annotation.SuppressLint
import android.content.Context
import android.content.DialogInterface
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.Gravity
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.DialogFragment
import com.google.gson.GsonBuilder
import com.smasher.domain.R
import com.smasher.domain.databinding.FragmentDomainQueryBinding
import com.smasher.domain.entity.BeanDomain

class DomainQueryFragment : DialogFragment() {

    private lateinit var mBinding: FragmentDomainQueryBinding

    private var mParam: String? = null
    private val gson = GsonBuilder().create()
    private var bean: BeanDomain? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NO_TITLE, 0)
        arguments?.let {
            mParam = it.getString(ARG_PARAM)
            if (!TextUtils.isEmpty(mParam)) {
                mParam?.let { t ->
                    parseBean(t)
                }
            }
        }
    }

    private fun parseBean(param: String) {
        try {
            bean = gson.fromJson(param, BeanDomain::class.java)
        } catch (e: Exception) {
            Log.i(TAG, "parseBean: error")
        }

    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        mBinding = FragmentDomainQueryBinding.inflate(inflater, container, false)
        return mBinding.root
    }

    @SuppressLint("DefaultLocale")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        mBinding.title.setText(R.string.domain_add)
        mBinding.protocolConfig.setText(R.string.domain_protocol)
        mBinding.protocolHttp.setText(R.string.domain_protocol_http)
        mBinding.protocolHttps.setText(R.string.domain_protocol_https)
        mBinding.protocolHttp.isEnabled = false
        mBinding.protocolHttps.isEnabled = false
        mBinding.ipConfig.setText(R.string.domain_ip)
        mBinding.ipContent.setHint(R.string.add_domain_hint_uri)
        mBinding.portConfig.setText(R.string.domain_port)
        mBinding.portContent.setHint(R.string.add_domain_hint_port)

        bean?.let {
            mBinding.protocolHttp.isChecked = it.scheme.equals("http")
            mBinding.protocolHttps.isChecked = it.scheme.equals("https")
            mBinding.ipContent.text = it.host
            mBinding.portContent.text = String.format("%d", it.port)
        }
    }

    override fun onStart() {
        super.onStart()
        val dialog = dialog
        if (dialog != null) {
            dialog.setCanceledOnTouchOutside(true)
            dialog.setOnKeyListener(keyListener)

            //初始化window相关表现
            val window = dialog.window
            //window.setBackgroundDrawableResource(android.R.color.transparent);
            if (window != null) {
                // 宽度（PX）
                val width = getPrimaryWith(requireContext())
                val params = window.attributes
                params.width = if (width != 0) {
                    (width * 0.9).toInt()
                } else {
                    WindowManager.LayoutParams.MATCH_PARENT
                }
                params.height = WindowManager.LayoutParams.WRAP_CONTENT
                //params.height = (int) (height * 0.8);
                params.gravity = Gravity.CENTER
                //params.horizontalMargin = 0.8f;
                window.attributes = params
            }
        }
    }

    private val keyListener =
        DialogInterface.OnKeyListener { _: DialogInterface?, _: Int, _: KeyEvent? -> false }

    private fun getPrimaryWith(context: Context): Int {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // For API level 30 and above, use WindowMetrics
            val windowMetrics = context.getSystemService(WindowManager::class.java)
                ?.currentWindowMetrics ?: return 0

            val insets = windowMetrics.windowInsets
                .getInsetsIgnoringVisibility(WindowInsetsCompat.Type.systemBars())

            val bounds = windowMetrics.bounds
            bounds.width() - insets.left - insets.right
        } else {
            val displayMetrics = context.resources.displayMetrics
            displayMetrics.widthPixels
        }
    }

    companion object {
        private const val ARG_PARAM = "param"
        const val TAG = "Category"

        /**
         * Use this factory method to create a new instance of
         * this fragment using the provided parameters.
         *
         * @param param Parameter 1.
         * @return A new instance of fragment CategoryFragment.
         */
        fun newInstance(param: String): DomainQueryFragment {
            return DomainQueryFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_PARAM, param)
                }
            }
        }
    }
}

